package org.execute.tool.adsPower;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Sleeper;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Main {
    private static final Logger logger = LoggerFactory.getLogger(Main.class);

    public static void main(String[] args) throws InterruptedException {
        // 1. 配置线程池参数
        int corePoolSize = 4; // 核心线程数（常驻线程）
        int maximumPoolSize = 5; // 最大线程数
        long keepAliveTime = 60; // 非核心线程空闲超时时间
        TimeUnit unit = TimeUnit.SECONDS; // 超时时间单位
        String filePath = "D:\\test\\test2.txt";
        String filePath2 = "D:\\test\\test3.txt";
        List<String> randomReply = readFileLines(filePath2);



        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(120); // 任务队列（容量为2）
        ThreadFactory threadFactory = new CustomThreadFactory(); // 线程工厂（自定义线程名）
        RejectedExecutionHandler handler = new ThreadPoolExecutor.CallerRunsPolicy(); // 拒绝策略
        // 2. 创建线程池（推荐方式）
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );

        // 1. 配置批量处理的参数
        String apiKey = "0ed9dba32c7c436448bea6aa50006cbc"; // 替换为实际API密钥
//        List<String> profileIds = new ArrayList<>();
//        profileIds.add("k150e38p");       // 配置ID1
//        profileIds.add("k150dtjw");   // 配置ID2（替换为实际ID）
        List<String> profileIds = readFileLines(filePath);



        AdspowerStart2 adspowerStart2 = new AdspowerStart2(apiKey, profileIds);

//        Map<String, AdsPowerWebAction> stringAdsPowerWebActionMap = adspowerStart2.openBrowserList();
        // 提交多个任务
        for (String profileId : profileIds) {

            executor.execute(() -> {

                AdsPowerWebAction adsPowerWebAction = null;
                try {
                    adsPowerWebAction = adspowerStart2.openBrowser(profileId);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }

//                task1(adsPowerWebAction);
                String random = getRandomElementFromList(randomReply);



                int number=3;
                boolean isSuccess=false;
                //关闭全标签
                adsPowerWebAction.closeAllTabs();
                boolean b = task3(adsPowerWebAction);
                for (int i = 0; i < number; i++) {

                    if (!b) {
                        task2(adsPowerWebAction,random);
                        adsPowerWebAction.waitMillis(30000);

                    }else {
                        isSuccess=true;
                        break;
                    }
                    b = task3(adsPowerWebAction);
                }
                // 4. 记录非成功数据：3次循环后仍未成功
                // 记录非成功数据到文件
                if (!isSuccess) {
                    String failureMessage = String.format(
                            "【任务最终失败】profileId: %s, 重试次数: %d次, 使用的回复内容: %s",
                            profileId,
                            number,
                            random
                    );
                    FileLogger.log(failureMessage);
                } else {
                    // 记录成功日志到文件
                    String successMessage = String.format(
                            "【任务成功】profileId: %s, 使用的回复内容: %s",
                            profileId,
                            random
                    );
                    FileLogger.log(successMessage);
                }
                try {
                    adspowerStart2.stopBrowser(profileId);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });

        }
        executor.shutdown(); // 关闭线程池，不再接受新任务
        try {
            // 等待所有已提交的任务执行完成（设置超时时间，根据实际任务耗时调整）
            // 这里设置1小时超时，可根据实际情况修改
            if (!executor.awaitTermination(1, TimeUnit.HOURS)) {
                // 如果超时，强制关闭未完成的任务
                executor.shutdownNow();
            }
        } catch (InterruptedException e) {
            // 若等待过程中被中断，强制关闭
            executor.shutdownNow();
        }
        Thread.sleep(2000); // 模拟任务耗时

        adspowerStart2.closeAll();

    }

    /**
     * 点击推特
     * @param webAction
     */
    public static void task1(AdsPowerWebAction webAction) {
        try {
            //关闭全标签
//            webAction.closeAllTabs();
            // 1. 导航到目标页面
            webAction.navigateTo("https://app.wardenprotocol.org/earn");
            webAction.waitForPageLoad();

            // 2. 关闭可能出现的弹窗
            By closePopupBtn = By.cssSelector("button.absolute.top-5.right-5.cursor-pointer svg.lucide-x");
            if (webAction.isElementPresent(closePopupBtn)) {
                webAction.clickElement(closePopupBtn);
                webAction.waitMillis(500); // 等待弹窗关闭
            }

            // 3. 点击"All 14"按钮
            // 修正后的按钮定位器（适配实际HTML结构）
            By all14BtnByClass = By.cssSelector("button.cursor-pointer.min-w-fit.ml-1");

            boolean elementPresent = webAction.isElementPresent(all14BtnByClass);
//            System.out.println(elementPresent);
            webAction.clickElement(all14BtnByClass);
            webAction.waitMillis(1000); // 等待展开

            // 4. 等待radix弹窗加载（动态ID处理，通过特征父元素定位）
            By radixContainer = By.cssSelector("div[role='dialog'][id^='radix-']"); // 匹配ID以radix-开头的dialog
            webAction.waitForElementVisible(radixContainer);

            // 5. 查找目标卡片（包含"Follow us on X"的元素）
            By targetCard = By.xpath("//div[contains(@class, 'border-[1px] bg-fill-elevated border-solid border-border-edge rounded-3xl') and .//div[text()='Follow us on X']]");
            webAction.waitForElementVisible(targetCard);
            WebElement cardElement = webAction.findElement(targetCard);

            // 6. 检查是否有"No daily limit"
            boolean hasNoDailyLimit = webAction.isElementPresent(
                    By.xpath(".//div[contains(text(), 'No daily limit')]"), cardElement);

            if (!hasNoDailyLimit) {
                // 7. 查找并点击Follow链接
                By followLink = By.xpath(".//a[contains(@class, 'h-6 px-2 rounded-2xl font-semibold text-xs') and text()='Follow']");
                if (webAction.isElementPresent(followLink, cardElement)) {
                    // 记录当前窗口句柄
                    String originalWindow = webAction.getCurrentWindowHandle();

                    // 点击Follow，打开新标签
                    webAction.clickElement(followLink, cardElement);
                    webAction.waitMillis(1000);

                    // 切换到新窗口并关闭
                    Set<String> allWindows = webAction.getDriver().getWindowHandles();
                    for (String window : allWindows) {
                        if (!window.equals(originalWindow)) {
                            webAction.switchToWindow(window);
                            webAction.waitMillis(1000); // 等待页面加载
                            webAction.getDriver().close(); // 关闭新标签
                            break;
                        }
                    }

                    // 切回原窗口
                    webAction.switchToWindow(originalWindow);
                    webAction.waitMillis(1000);

                    // 8. 点击出现的Validate按钮
                    By validateBtn = By.xpath(".//button[contains(@class, 'h-6 px-2 rounded-2xl font-semibold text-xs') and text()='Validate']");
                    webAction.waitForElementVisible(validateBtn, cardElement);
                    webAction.clickElement(validateBtn, cardElement);
                    webAction.waitMillis(500);
                }
            }

        } catch (Exception e) {
            System.err.println("任务执行出错: " + e.getMessage());
            e.printStackTrace();
            try {
                // 出错时截图保存
                String screenshotPath = webAction.takeScreenshot();
                System.out.println("错误截图已保存至: " + screenshotPath);
            } catch (IOException ioe) {
                System.err.println("截图保存失败: " + ioe.getMessage());
            }
        }
    }

    /**
     * 处理USDC转换交互流程
     * @param webAction AdsPowerWebAction实例
     */
    public static void task2(AdsPowerWebAction webAction,String  random) {
        try {

            // 1. 导航到dashboard页面
            webAction.navigateTo("https://app.wardenprotocol.org/dashboard");
            webAction.waitForPageLoad(); // 等待页面加载完成
            String targetCss = "#wallet-menu-button span.text-base";


//            webAction.waitMillis(15000);
            webAction.waitForElementVisible(By.cssSelector(targetCss));
            WebElement nameSpan = webAction.findElement(By.cssSelector(targetCss));

//            System.out.println("targetCss"+ nameSpan.getAttribute("outerHTML"));

            // 2. 调用extractUSDCData获取USDC数据
            Map<String, Double> usdcData = extractUSDCData(webAction);
            Double usdcValue = usdcData.get("USD Coin"); // 获取USDC数值
            System.out.println("获取到的USDC数值: " + usdcValue);

            // 3. 根据USDC数值判断使用的语句（此处需补充具体判断条件）
            String inputText;
            if (usdcValue==null||usdcValue< 5) { // 示例条件：大于100使用语句1，否则使用语句2
                inputText = random; // 替换为实际语句2
            } else {
                inputText = "convert all USDC to BASE eth "; // 替换为实际语句1

            }

            // 4. 定位textarea元素并输入文字
            By textareaLocator = By.cssSelector(
                    "#chat-form-desktop textarea"
            );
            WebElement textarea = webAction.findElement(textareaLocator);

            // 输入判断后的语句并按回车
            textarea.clear(); // 清空输入框（可选，根据实际需求）
            textarea.sendKeys(inputText);
            textarea.sendKeys(Keys.ENTER); // 按回车提交
            System.out.println("已输入: " + inputText + " 并提交");
            Random randomN = new Random();

            //重新定位
            textarea = webAction.findElement(textareaLocator);

            // 5. 输入"yes"并等待
            textarea.clear(); // 清空输入框（可选，根据实际需求）
            textarea.sendKeys("yes"); // 模拟手动输入yes

            webAction.waitForAnyElementPresent(By.id("stream-send"));
            textarea = webAction.findElement(textareaLocator);

            textarea.sendKeys(Keys.ENTER); // 按回车提交

            System.out.println("已输入: yes 并提交");

            // 再等待5-10秒（此处取7秒示例）
            // 5. 输入"yes"并等待
            textarea.clear(); // 清空输入框（可选，根据实际需求）
            textarea.sendKeys("yes"); // 模拟手动输入yes
            webAction.waitForAnyElementPresent(By.id("stream-send"));
            textarea.clear(); // 清空输入框（可选，根据实际需求）


        } catch (Exception e) {
            System.err.println("任务2执行出错: " + e.getMessage());
            e.printStackTrace();
            try {
                String screenshotPath = webAction.takeScreenshot();
                System.out.println("错误截图已保存至: " + screenshotPath);
            } catch (IOException ioe) {
                System.err.println("截图保存失败: " + ioe.getMessage());
            }
        }
    }

    public static boolean task3(AdsPowerWebAction webAction) {
        try {
            //关闭全标签
//            webAction.closeAllTabs();
            // 1. 导航到目标页面
            webAction.navigateTo("https://app.wardenprotocol.org/earn");
            webAction.waitForPageLoad();

            // 2. 关闭可能出现的弹窗
            By closePopupBtn = By.cssSelector("button.absolute.top-5.right-5.cursor-pointer svg.lucide-x");
            if (webAction.isElementPresent(closePopupBtn)) {
                webAction.clickElement(closePopupBtn);
                webAction.waitMillis(500); // 等待弹窗关闭
            }

            // 3. 点击"All 14"按钮
            // 修正后的按钮定位器（适配实际HTML结构）
            By all14BtnByClass = By.cssSelector("button.cursor-pointer.min-w-fit.ml-1");

            boolean elementPresent = webAction.isElementPresent(all14BtnByClass);
            System.out.println(elementPresent);
            webAction.clickElement(all14BtnByClass);
            webAction.waitMillis(1000); // 等待展开

            // 4. 等待radix弹窗加载（动态ID处理，通过特征父元素定位）
            By radixContainer = By.cssSelector("div[role='dialog'][id^='radix-']"); // 匹配ID以radix-开头的dialog
            webAction.waitForElementVisible(radixContainer);

            // 5. 查找目标卡片（包含"Follow us on X"的元素）
            By targetCard = By.xpath("//div[contains(@class, 'border-[1px] bg-fill-elevated border-solid border-border-edge rounded-3xl') and .//div[text()='Token Swap']]");
            webAction.waitForElementVisible(targetCard);
            WebElement cardElement = webAction.findElement(targetCard);

            // 6. 检查是否有"No daily limit"
            boolean hasNoDailyLimit = webAction.isElementPresent(
                    By.xpath(".//div[contains(text(), 'No daily limit')]"), cardElement);

            return hasNoDailyLimit;

        } catch (Exception e) {
            System.err.println("任务执行出错: " + e.getMessage());
            e.printStackTrace();
            try {
                // 出错时截图保存
                String screenshotPath = webAction.takeScreenshot();
                System.out.println("错误截图已保存至: " + screenshotPath);
            } catch (IOException ioe) {
                System.err.println("截图保存失败: " + ioe.getMessage());
            }
            return false;
        }
    }

    // 自定义线程工厂（用于设置线程名，便于调试）
    static class CustomThreadFactory implements ThreadFactory {
        private final AtomicInteger count = new AtomicInteger(1);

        @Override
        public Thread newThread(Runnable r) {
            Thread thread = new Thread(r, "custom-thread-" + count.getAndIncrement());
            thread.setDaemon(false); // 非守护线程
            thread.setPriority(Thread.NORM_PRIORITY); // 正常优先级
            return thread;
        }
    }

    /**
     * 读取文本文件的每一行到List中
     * @param filePath 文件路径
     * @return 包含文件每行内容的List，如果发生错误则返回null
     */
    public static List<String> readFileLines(String filePath) {
        // 创建一个ArrayList来存储文件的每一行
        List<String> lines = new ArrayList<>();

        // 使用try-with-resources语法，确保资源自动关闭
        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            // 逐行读取文件内容
            while ((line = br.readLine()) != null) {
                // 将读取到的行添加到List中
                lines.add(line);
            }
            return lines;
        } catch (IOException e) {
            // 处理可能出现的IO异常
            System.err.println("读取文件时发生错误：" + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }
    /**
     * 提取USDC相关数据（需提前确保已导航到目标页面）
     * @param webAction AdsPowerWebAction实例
     * @return 提取的USDC数据map，key为"name"，value为数值型数值
     * @throws IllegalArgumentException 当webAction为null时抛出
     * @throws TimeoutException 当元素超时未加载时抛出
     * @throws NoSuchElementException 当元素不存在时抛出
     */
    public static Map<String, Double> extractUSDCData(AdsPowerWebAction webAction) {
        if (webAction == null) {
            throw new IllegalArgumentException("AdsPowerWebAction实例不能为空");
        }

        // 定义元素定位器（与JS中选择器对应）
        By buttonSelector = By.cssSelector(
                "button.rounded-\\[20px\\].py-3\\.5.px-4.flex.gap-4.items-center.justify-start.bg-fill-elevated.w-full"
        );
        String nameCss = "span.block.text-left span.block.text-xs.text-label-secondary";
        String valueCss = "span.block.text-right span.block:first-of-type";



//        webAction.waitForElementPresent(buttonSelector); // 等待textarea可见
        webAction.waitMillis(2000);
        // 等待按钮元素加载并获取列表

        List<WebElement> buttons = webAction.findElements(buttonSelector);

        Map<String, Double> resultMap = new HashMap<>();

        // 遍历按钮查找USD Coin数据
        for (WebElement button : buttons) {
//            System.out.println("button"+ button.getAttribute("outerHTML"));
            WebElement nameSpan = button.findElement(By.cssSelector(nameCss));
            String name = nameSpan.getText().trim();
            if (name.isEmpty()) {
                name=nameSpan.getAttribute("textContent").trim();
            }
//            System.out.println("nameSpan"+ nameSpan.getAttribute("outerHTML"));
            WebElement valueSpan = button.findElement(By.cssSelector(valueCss));
            String valueText = valueSpan.getText().trim();
            if (valueText.isEmpty()) {
                valueText=valueSpan.getAttribute("textContent").trim();
            }
//            System.out.println("valueSpan"+ valueSpan.getAttribute("outerHTML"));
            // 处理数值格式（移除非数字和小数点字符）
            String numericValueStr = valueText.replaceAll("[^0-9.]", "");
            if (!numericValueStr.isEmpty()) {
                Double numericValue = Double.parseDouble(numericValueStr);
                resultMap.put(name, numericValue);
            }

        }

        return resultMap; // 找到后立即返回
    }
    public static <T> T getRandomElementFromList(List<T> list) {
        // 先判断 List 是否为空，避免空指针或索引越界
        if (list == null || list.isEmpty()) {
            System.out.println("List 为空，无法获取随机元素");
            return null; // 或抛异常，根据业务需求调整
        }

        // 创建 Random 实例，生成 0 ~ list.size()-1 的随机索引
        Random random = new Random();
        int randomIndex = random.nextInt(list.size()); // nextInt(n) 生成 [0, n) 的整数

        // 根据随机索引返回元素
        return list.get(randomIndex);
    }
}
